$(function() {

    var console = window.console || { log: function() {} };
    var URL = window.URL || window.webkitURL;
    var $image = $('#imageCover');
    var options = {
        aspectRatio: 4 / 3, //裁剪框比例1:1
        // preview: '.img-preview', //预览图
        viewMode: 1,
        minCropBoxWidth: 100 //裁剪最小宽度
    };
    var originalImageURL = $image.attr('src');
    var uploadedImageURL;


    // Cropper
    $image.on({
        ready: function(e) {
            // console.log(e.type);
        }
    }).cropper(options);


    // Buttons
    if (!$.isFunction(document.createElement('canvas').getContext)) {
        $('button[data-method="getCroppedCanvas"]').prop('disabled', true);
    }

    // Methods
    $('.coverLayer').on('click', '[data-method]', function() {
        var $this = $(this);
        var data = $this.data();
        var $target;
        var result;

        if ($this.prop('disabled') || $this.hasClass('disabled')) {
            return;
        }

        if ($image.data('cropper') && data.method) {
            data = $.extend({}, data); // Clone a new one

            if (typeof data.target !== 'undefined') {
                $target = $(data.target);

                if (typeof data.option === 'undefined') {
                    try {
                        data.option = JSON.parse($target.val());
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            }

            if (data.method === 'rotate') {
                $image.cropper('clear');
            }

            result = $image.cropper(data.method, data.option, data.secondOption);

            if (data.method === 'rotate') {
                $image.cropper('crop');
            }

            switch (data.method) {
                case 'scaleX':
                case 'scaleY':
                    $(this).data('option', -data.option);
                    break;

                case 'getCroppedCanvas': //上传头像
                    if (result) {
                        var imgBase = result.toDataURL('image/jpeg');
                        $.ajax({
                            url: 'upload.php',
                            type: 'POST',
                            data: { imgBase: imgBase },
                            dataType:'json',
                            success: function (res) {
                                if (res.code == '0') {

                                    layer.closeAll();
                                    $('#avatar').attr('src',res.data);

                                    console.log('上传成功');
                                } else {
                                    console.log('上传失败');
                                }
                            },
                            error:function(){
                                layer.msg('请求失败，请稍后再试！');
                            }
                        });
                    }
                    break;

                case 'destroy':
                    if (uploadedImageURL) {
                        URL.revokeObjectURL(uploadedImageURL);
                        uploadedImageURL = '';
                        $image.attr('src', originalImageURL);
                    }
                    break;
            }

            if ($.isPlainObject(result) && $target) {
                try {
                    $target.val(JSON.stringify(result));
                } catch (e) {
                    console.log(e.message);
                }
            }

        }
    });


    // Keyboard
    $(document.body).on('keydown', function(e) {

        if (!$image.data('cropper') || this.scrollTop > 300) {
            return;
        }

        switch (e.which) {
            case 37:
                e.preventDefault();
                $image.cropper('move', -1, 0);
                break;

            case 38:
                e.preventDefault();
                $image.cropper('move', 0, -1);
                break;

            case 39:
                e.preventDefault();
                $image.cropper('move', 1, 0);
                break;

            case 40:
                e.preventDefault();
                $image.cropper('move', 0, 1);
                break;
        }

    });


    // 重新上传
    var $changeImg = $('#inputImage');

    if (URL) {
        $changeImg.change(function() {
            var files = this.files;
            var file;

            if (!$image.data('cropper')) {
                return;
            }

            if (files && files.length) {
                file = files[0];

                if (/^image\/\w+$/.test(file.type)) {
                    if (uploadedImageURL) {
                        URL.revokeObjectURL(uploadedImageURL);
                    }

                    uploadedImageURL = URL.createObjectURL(file);
                    $image.cropper('destroy').attr('src', uploadedImageURL).cropper(options);
                    $changeImg.val('');
                } else {
                    window.alert('请选择一张图片上传.');
                }
            }
        });
    } else {
        $changeImg.prop('disabled', true).parent().addClass('disabled');
    }

    // 编辑头像
    $('.edit_tx').on('click',function(){
        layer.open({
            type: 1,
            title: false,
            closeBtn: 0,
            shadeClose: true,
            shade: 0.7,
            area: ['600px', '476px'], //宽高
            skin: 'cover_layer',
            content: $('.coverLayer')
        });
    })

    // 关闭图像裁剪弹窗
    $('body').on('click','.close_cover', function(){
        layer.closeAll()
    })

});